import {type ClassValue, clsx} from "clsx"
import {twMerge} from "tailwind-merge"
import {JWTPayload, jwtVerify, SignJWT} from "jose";
import {addDays, formatDate} from "date-fns";
import {randomUUID} from "node:crypto";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}


// 生成 JWT 函数
export async function generateToken(payload: Record<string, unknown>): Promise<string> {
  // 当前时间戳
  const iat = new Date();
  // 令牌有效期为 1 小时
  const exp = addDays(iat,7);

  const encoder = new TextEncoder();
  return await new SignJWT(payload)
      .setProtectedHeader({alg: 'HS256'})
      .setIssuedAt(iat)
      .setExpirationTime(exp)
      .sign(encoder.encode(process.env.USER_TOKEN_SECRET));
}

// 验证 JWT 函数（可选）
export async function verifyToken(token: string): Promise<JWTPayload> {
  try {
    const { payload } = await jwtVerify(token, new TextEncoder().encode(process.env.USER_TOKEN_SECRET));
    return payload;
  } catch (e) {
    throw new Error('Invalid token'+e?.toString());
  }
}


export const getSearchParams = (data:{[key:string]:unknown}) => {
  const entries = Object.entries(data);
  const searchParams: URLSearchParams = new URLSearchParams();

  for (let i = 0; i < entries.length; i++) {
    const item = entries[i];
    if(
        typeof item[1] === 'string' ||
        typeof item[1] === 'boolean' ||
        typeof item[1] === 'number'
    ){
      searchParams.append(item[0], item[1].toString());
    }else if(item[1] instanceof File){
      throw new Error("不能转化文件参数");
    }else if(item[1] instanceof Date){
      searchParams.append(item[0], formatDate(item[1],"yyyy-MM-dd HH:mm:ss"));
    }else {
      searchParams.append(item[0],encodeURIComponent(JSON.stringify(item[1])));
    }
  }

  return   searchParams;
}